const express = require('express');
const router = express.Router();
const User = require('../models/user');

// 创建用户
router.post('/', async (req, res) => {
    try {
        const user = new User(req.body);
        await user.save();
        res.status(201).json(user);
    } catch (error) {
        res.status(400).json({ message: error.message });
    }
});

// 获取用户列表（支持分页）
router.get('/', async (req, res) => {
    try {
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 10;
        const skip = (page - 1) * limit;

        const users = await User.find()
            .skip(skip)
            .limit(limit)
            .sort({ uid: 1 });

        const total = await User.countDocuments();

        res.json({
            data: users,
            pagination: {
                current: page,
                pageSize: limit,
                total
            }
        });
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
});

// 获取单个用户
router.get('/:uid', async (req, res) => {
    try {
        const user = await User.findOne({ uid: parseInt(req.params.uid) });
        if (!user) {
            return res.status(404).json({ message: '用户不存在' });
        }
        res.json(user);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
});

// 更新用户
router.put('/:uid', async (req, res) => {
    try {
        const user = await User.findOneAndUpdate(
            { uid: parseInt(req.params.uid) },
            req.body,
            { new: true, runValidators: true }
        );
        if (!user) {
            return res.status(404).json({ message: '用户不存在' });
        }
        res.json(user);
    } catch (error) {
        res.status(400).json({ message: error.message });
    }
});

// 删除用户
router.delete('/:uid', async (req, res) => {
    try {
        const user = await User.findOneAndDelete({ uid: parseInt(req.params.uid) });
        if (!user) {
            return res.status(404).json({ message: '用户不存在' });
        }
        res.json({ message: '用户已删除' });
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
});

module.exports = router; 